package com.atguigu.mapreduce.mapjoin;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;

public class MapJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

    private HashMap<String, String> pdMap = new HashMap();
    private Text outK = new Text();

    //任务开始前将pd数据缓存进pdMap
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {

        //通过缓存文件得到小表数据pd.txt
        //（获取缓存文件的方法context.getCacheFiles()返回值是一个URI数组）
        URI[] cacheFiles = context.getCacheFiles();

        // 获取文件系统对象,并开流
        FileSystem fs = FileSystem.get(context.getConfiguration());
        FSDataInputStream fis = fs.open(new Path(cacheFiles[0]));

        // 从流中读取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));

        // 逐行读取，按行处理
        String line;
        while (StringUtils.isNotEmpty(line = reader.readLine())) {

            // 切割
            String[] split = line.split("\t");
            // 赋值
            pdMap.put(split[0], split[1]);

        }

        // 关流
        IOUtils.closeStream(reader);

    }

    // 处理order.txt
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

        // 读取大表数据，并按行处理，切割
        String[] fields = value.toString().split("\t");

        // 获取到每一行对应的pid，在pdMap中找到对应的pdname
        String pdname = pdMap.get(fields[1]);

        // 封装outK
        outK.set(fields[0] + "\t" + pdname + "\t" + fields[2]);

        // 写出
        context.write(outK,NullWritable.get());
    }
}
